// pages/orderdetail/orderdetail.js
const httpUtils = require('../../utils/httpUtils.js');
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://yxpmaterial.sse100.com/shop/',
    num: 0, //可激活数
    binding: 0, //0展示1绑定 2完善个人信息
    id: 0,
    order_no: "",
    mData: null,
    cursedetail: "", //课程包含
    codetime: "获取验证码",
    phone: "",
    code: "",
    totleTime: 60,
    isShow:true,
    isDaojishi: false,
    gradeName:'请选择年级',
    gradeId:0,
    gradeData:[],
    isBoy: 1,
    isGirl: 0,
    name:"",
    activatedPhone: "", // 激活的手机号 
    password: "", // 密码（手机号后六位） 
    activateTime: "", // 激活时间 
    studentInfo: null, // 学生信息 
    isOldUser: false,
    isPhysical: false, // 是否为实物订单
    logisticsNo: null // 物流单号
  },
  selectBoy: function () {
    let that = this
    that.setData({
      isBoy: 1,
      isGirl: 0
    })
  },
  selectGirl: function () {
    let that = this
    that.setData({
      isBoy: 0,
      isGirl: 1

    })
  },
  phoneChange: function (e) {
    let that = this;
    that.setData({
      phone: e.detail.value
    })

  },
  codeChange: function (e) {
    let that = this;
    that.setData({
      code: e.detail.value
    })

  },
  nameChange:function(e){
    let that = this;
    that.setData({
      name: e.detail.value
    })
  },
  getCode: function () {
    let that = this;
    if (!that.isDaojishi) {
      that.sendCode()
    }


  },
  sendCode: function () {
    let that = this;
    if (that.data.phone == "") {
      wx.showToast({
        title: "请输入手机号",
        icon: 'none',
        duration: 2000
      })
      return
    }
    //格式验证
    if (!/^1[3-9]\d{9}$/.test(that.data.phone)) { 
        wx.showToast({ 
          title: "请输入正确的手机号", 
          icon: 'none', 
          duration: 2000 
        }) 
        return 
      } 
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.sendmsg({
      username: that.data.phone,
      type: 1
    }).then((res) => {

      if (res.code == 1) {
        that.setData({
          codetime: "60s",
          isDaojishi: true
        })
        that.daojishi();
      } else {
        wx.showToast({
          title: res.msg || "验证码发送失败",
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: "网络错误，请重试",
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 倒计时
   */
  daojishi: function () {
    let that = this;
    that.data.timer = setInterval(function () {

      if (that.data.isDaojishi) {
        let num = that.data.totleTime - 1;
        that.setData({
          codetime: num + "s",
          totleTime: num
        });
        //倒计时结束
        if (that.data.totleTime <= 0) {
          that.setData({
            isDaojishi: false,
            totleTime: 60,
            codetime: "获取验证码"
          })
        }
      }

    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      order_no: options.order_no
    })
    this.getData();
  },
  getData: function () {
    let that = this
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.orderProduct({
      access_token: app.globalData.$TOKEN,
      order_no: that.data.order_no,
      product_id: that.data.id

    }).then((res) => {
      wx.hideLoading()
      if (res.code == 1) {
        console.log('订单详情数据:', res.data)
        const orderData = res.data;
        // 判断是否为实物订单
        const isPhysical = !!orderData.order;

        // 根据订单类型设置数据
        let logisticsNo = null;
        let activatedPhone = '';
        let unactiveNum = 0
        if (isPhysical) {
            // 实物订单数据
            logisticsNo = orderData.order ? orderData.order.logistics_no : null;
          } else {
            // 课程订单数据
            activatedPhone = orderData.student ? orderData.student.mobile : '';
          }
        const password = activatedPhone ? activatedPhone.slice(-6) : '';
        
        this.setData({
          mData: res.data,
          num: res.data.unactive_num,
          phone: '',
          code: '',
          name: '',
          gradeName: "请选择年级",
          gradeId: 0,
          binding: 0,
          activatedPhone: activatedPhone,
          password: password,
          isPhysical: isPhysical,
          logisticsNo: logisticsNo,
          isOldUser: false
        })
      }else {
        wx.showToast({
          title: res.msg || "数据加载失败",
          icon: 'none',
          duration: 5000
        })
      }
    }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: "网络错误，请重试",
          icon: 'none',
          duration: 2000
        })
    })
  },
  getGrade: function () {
    let that = this
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.getgrade({
      access_token: app.globalData.$TOKEN,

    }).then((res) => {
      wx.hideLoading()

      this.setData({
        gradeData: res.data,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 清理定时器
    if (this.data.timer) {
        clearInterval(this.data.timer);
    }
    // 返回时跳转到订单列表页
    wx.switchTab({
        url: '/pages/orderlist/orderlist',
        fail: (err) => {
          console.warn('跳转订单列表失败', err);
        }
      });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 用户点击右上角返回
   */
  goBack: function() {
    // 返回到订单列表页
    wx.switchTab({
        url: '/pages/orderlist/orderlist'
    });
  },

  /**
   * 分享
   */
  goShare: function () {

  },
  /**
   * 激活界面
   */
  goBind: function () {
    if (this.data.num <= 0) {
      return
    }
    this.setData({
      binding: 1
    })

  },

  /**
   * 验证码和完善信息提交
   */
  bindCard: function () {
    let that = this;
    console.log("that.data.binding:"+that.data.binding)
    if (that.data.binding==1) {
      // 手机号验证阶段 
      if (this.data.phone == "") {
        wx.showToast({
          title: "请输入手机号",
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (!/^1[3-9]\d{9}$/.test(that.data.phone)) { 
        wx.showToast({ 
          title: "请输入正确的手机号", 
          icon: 'none', 
          duration: 2000 
        }) 
        return 
      } 
      if (this.data.codetime == "") {
        wx.showToast({
          title: "请输入手机验证码",
          icon: 'none',
          duration: 2000
        })
        return
      }
      that.checkMobile();
    }else{
      //完善信息阶段
      if (this.data.name == "") {
        wx.showToast({
          title: "请输入姓名",
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (this.data.gradeId == 0) {
        wx.showToast({
          title: "请选择年级",
          icon: 'none',
          duration: 2000
        })
        return
      }
      that.courseActivate()
    }
  
   
  },
  courseActivate: function () {
    let that = this
    wx.showLoading({
      title: '正在激活',
      mask: true
    })
    httpUtils.courseActivate({
      access_token: app.globalData.$TOKEN,
      order_no: that.data.order_no,
      product_id: that.data.id,
      mobile: that.data.phone,
      name: that.data.name,
      sex: that.data.mIsBoy == 1 ? "1" : "2",
      gradeid: that.data.gradeId,

    }).then((res) => {
      wx.hideLoading()
      if (res.code == 1) {
        const now = new Date();
        const activateTime = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
        // 激活成功，显示提示弹窗
        that.setData({
            activatedPhone: that.data.phone,
            password: that.data.phone.slice(-6), // 手机号后六位作为密码
            activateTime: activateTime,
            isShow: false
        })
         

        // 更新激活数量
        that.setData({
            num: that.data.num - 1,
        })
      }else {
        wx.showToast({
          title: res.msg || "激活失败",
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: "网络错误，请重试",
          icon: 'none',
          duration: 2000
        })
    })
  },
  checkMobile: function () {
    let that = this;
    wx.showLoading({
      title: '正在验证',
      mask: true
    })
    httpUtils.checkMobile({
      access_token: app.globalData.$TOKEN,
      order_no: that.data.order_no,
      product_id: that.data.id,
      mobile: that.data.phone,
      code: that.data.code

    }).then((res) => {
      wx.hideLoading()
      if (res.code == 1) {
        if (res.data.code == 10032) {
            // 处理手机号已有课程的情况
            that.setData({
              phone: '',
              code: ''
            });
            wx.showToast({
              title: "您输入的手机号码已激活当前课程，请更换手机号激活",
              icon: 'none',
              duration: 3000
            })
        } else{
           // 根据返回的type判断新老用户，显示返回的学生信息
        const studentInfo = res.data.student || null;
        const isOldUser = (res.data.type === 1) && studentInfo;
        if (isOldUser) {
          // 老用户，填充已有数据
          that.setData({
            name: studentInfo.username || '',
            gradeId: studentInfo.gradeid || 0,
            gradeName: studentInfo.gradename || '加载中...',
            isBoy: studentInfo.sex === 1 ? 1 : 0,
            isGirl: studentInfo.sex === 2 ? 1 : 0,
            studentInfo: studentInfo,
            isOldUser: true 
          });
          // 获取年级列表并匹配名称
          that.getGradeAndSetGradeName(studentInfo.gradeid);
        } else {
          // 新用户，清空数据
          that.setData({
            name: '',
            gradeName: '请选择年级',
            gradeId: 0,
            isBoy: 1,
            isGirl: 0,
            isOldUser: false
          });
          // 获取年级数据并进入完善信息环节
          that.getGrade();
        }
        
        that.setData({
          binding: 2
        }) 
        }
         
      } else {
        that.setData({
            code: ''
          });
        wx.showToast({
          title: res.msg || "验证失败",
          icon: 'none',
          duration: 3000
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: "网络错误，请重试",
        icon: 'none',
        duration: 2000
      })
    })
  },
  bindPickerChange: function (e) {
    let that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      gradeName: that.data.gradeData[e.detail.value].grade_name,
      gradeId:that.data.gradeData[e.detail.value].grade,
    })
  },
  know:function(){
    let that = this;
    that.setData({
      isShow:true
    })
    that.getData();
  },

  getGradeAndSetGradeName: function (gradeId) {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    });
    httpUtils.getgrade({
      access_token: app.globalData.$TOKEN,
    }).then((res) => {
      wx.hideLoading();
      if (res.code === 1 && Array.isArray(res.data)) {
        const gradeData = res.data;
        let gradeName = '请选择年级';
  
        // 查找匹配的年级名称
        const matched = gradeData.find(item => item.grade === gradeId);
        if (matched) {
          gradeName = matched.grade_name;
        }
  
        that.setData({
          gradeData: gradeData,
          gradeName: gradeName
        });
      } else {
        that.setData({
          gradeData: [],
          gradeName: '请选择年级'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: "年级数据加载失败",
        icon: 'none',
        duration: 2000
      });
      that.setData({
        gradeData: [],
        gradeName: '请选择年级'
      });
    });
  },

  goToWatchStudy: function () { 
    wx.navigateTo({ 
      url: '/pages/webview/webview?url=' + encodeURIComponent('https://mp.weixin.qq.com/s/8J_BW5qT30b4zbT4ouH6IA') 
    }) 
  }, 

  contanctService: function () {
    wx.openCustomerServiceChat({
        extInfo: {url: 'https://work.weixin.qq.com/kfid/kfcd3340d9b38e56d5c'},//客服链接
        corpId: 'ww728dc86e04f7a617',//企业id
        success(res) {
            console.log('启动微信客服成功',res)
        },
        fail(err) {
            console.log('启动微信客服失败',err)
            wx.showModal({
                content: JSON.stringify(err),
                cancelColor: 'cancelColor',
            })
        }
      })
  },

  copyLogisticsNo: function(){
    let that = this;
    if (that.data.logisticsNo) {
      wx.setClipboardData({
        data: that.data.logisticsNo,
        success: function() {
          wx.showToast({
            title: '快递单号已复制',
            icon: 'success',
            duration: 2000
          })
        },
        fail: function() {
          wx.showToast({
            title: '复制失败，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }
})